from django.http import JsonResponse
from rest_framework.views import APIView
from allmodels.models import SysRole, SysRoleMenu  # 假设角色模型在 allmodels 中
from django.core.paginator import Paginator
from django.db.models import Q
from login.views import verify_token  # 假设已经有验证 token 的函数
import json
from django.db import transaction
from datetime import datetime


class RolePageView(APIView):
    def get(self, request, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 获取查询参数
        keywords = request.GET.get('keywords', '')
        start_date = request.GET.get('startDate', '')
        end_date = request.GET.get('endDate', '')
        page_num = int(request.GET.get('pageNum', 1))
        page_size = int(request.GET.get('pageSize', 10))

        # 构建查询条件
        filters = Q()
        if keywords:
            filters &= Q(name__icontains=keywords) | Q(code__icontains=keywords)

        if start_date and end_date:
            filters &= Q(create_time__range=[start_date, end_date])

        # 查询角色
        roles_query = SysRole.objects.filter(filters).order_by('sort')
        paginator = Paginator(roles_query, page_size)
        roles_page = paginator.get_page(page_num)
        # 如果status为true返回1反之0
        for role in roles_page:
            role.status = 1 if role.status else 0

        # 构建返回的数据结构
        role_list = []
        for role in roles_page:
            role_list.append({
                "id": role.id,
                "name": role.name,
                "code": role.code,
                "status": role.status,
                "sort": role.sort,
                "createTime": role.create_time.strftime('%Y-%m-%d %H:%M:%S') if role.create_time else None,
                "updateTime": role.update_time.strftime('%Y-%m-%d %H:%M:%S') if role.update_time else None
            })

        # 返回分页数据
        return JsonResponse({
            "code": "00000",
            "data": {
                "list": role_list,
                "total": paginator.count
            },
            "msg": "一切ok"
        })


class RoleOptionsView(APIView):
    def get(self, request, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 获取角色数据
        roles = SysRole.objects.all().order_by('sort')

        # 构建下拉列表选项
        role_options = []
        for role in roles:
            role_options.append({
                "value": role.id,
                "label": role.name,
                "children": []  # 如果有子选项可以在此添加
            })

        # 返回选项数据
        return JsonResponse({
            "code": "00000",
            "data": role_options,
            "msg": "操作成功"
        })


class CreateRoleView(APIView):
    def post(self, request, *args, **kwargs):
        # 获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 解析请求体
            data = json.loads(request.body)

            # 验证必填参数
            if 'name' not in data or 'code' not in data:
                return JsonResponse({
                    'code': '10006',
                    'msg': '角色名称和编码为必填项'
                }, status=400)

            # 在事务中保存角色信息
            with transaction.atomic():
                role = SysRole(
                    name=data['name'],
                    code=data['code'],
                    sort=data.get('sort', 0),  # 排序默认为0
                    status=data.get('status', 1),  # 状态默认为1（启用）
                    data_scope=data.get('dataScope', 0),  # 数据权限默认为0
                    create_by=payload.get('user_id', None),  # 设置创建者
                    create_time=datetime.now()  # 设置创建时间
                )
                role.save()

            return JsonResponse({
                'code': '00000',
                'msg': '角色创建成功',
                'data': {
                    'id': role.id,
                    'name': role.name,
                    'code': role.code,
                    'sort': role.sort,
                    'status': role.status,
                    'dataScope': role.data_scope
                }
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': '10007',
                'msg': '请求体格式错误'
            }, status=400)

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)

class GetRoleFormView(APIView):
    def get(self, request, role_id, *args, **kwargs):
        # 获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 根据 role_id 获取角色信息
            role = SysRole.objects.get(id=role_id)

            # 返回角色的表单数据
            return JsonResponse({
                'code': '00000',
                'data': {
                    'id': role.id,
                    'name': role.name,
                    'code': role.code,
                    'sort': role.sort,
                    'status': role.status,
                    'dataScope': role.data_scope
                },
                'msg': '角色信息获取成功'
            })

        except SysRole.DoesNotExist:
            return JsonResponse({
                'code': '10006',
                'msg': '角色不存在'
            }, status=404)

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)


class UpdateRoleView(APIView):
    def put(self, request, id, *args, **kwargs):
        # 获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 获取请求中的 JSON 数据
            data = json.loads(request.body)

            # 查找角色，如果不存在则返回错误
            role = SysRole.objects.get(id=id)

            # 更新角色的字段
            role.name = data.get('name', role.name)
            role.code = data.get('code', role.code)
            role.sort = data.get('sort', role.sort)
            role.status = data.get('status', role.status)
            role.data_scope = data.get('dataScope', role.data_scope)
            role.update_by = payload.get('user_id', None)  # 设置更新者
            role.update_time = datetime.now()  # 设置更新时间

            # 保存更新
            role.save()

            return JsonResponse({
                'code': '00000',
                'data': {
                    'id': role.id,
                    'name': role.name,
                    'code': role.code,
                    'sort': role.sort,
                    'status': role.status,
                    'dataScope': role.data_scope
                },
                'msg': '角色更新成功'
            })

        except SysRole.DoesNotExist:
            return JsonResponse({
                'code': '10006',
                'msg': '角色不存在'
            }, status=404)

        except json.JSONDecodeError:
            return JsonResponse({
                'code': '10007',
                'msg': '请求体格式错误'
            }, status=400)

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)

class DeleteRoleView(APIView):
    def delete(self, request, ids, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 处理删除角色的逻辑
        try:
            role_ids = [int(id) for id in ids.split(',') if id.isdigit()]  # 分割并转为整数
            if not role_ids:
                return JsonResponse({
                    'code': '10006',
                    'msg': '角色ID不能为空或无效'
                }, status=400)

            with transaction.atomic():
                # 删除角色
                SysRole.objects.filter(id__in=role_ids).delete()

            return JsonResponse({
                'code': '00000',
                'msg': '角色删除成功',
                'data': {}
            })

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'删除失败: {str(e)}'
            }, status=500)

class GetRoleMenuIdsView(APIView):
    def get(self, request, role_id, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 根据 role_id 查找菜单ID集合
            menu_ids = SysRoleMenu.objects.filter(role_id=role_id).values_list('menu_id', flat=True)
            return JsonResponse({
                'code': '00000',
                'data': list(menu_ids),
                'msg': '操作成功'
            })

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)

class AssignRoleMenusView(APIView):
    def put(self, request, role_id, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 解析请求体中的菜单ID集合
            data = json.loads(request.body)
            if not isinstance(data, list) or not all(isinstance(menu_id, int) for menu_id in data):
                return JsonResponse({
                    'code': '10006',
                    'msg': '菜单ID集合格式不正确'
                }, status=400)

            # 开始事务处理
            with transaction.atomic():
                # 删除当前角色的所有菜单权限
                SysRoleMenu.objects.filter(role_id=role_id).delete()

                # 分配新的菜单权限
                for menu_id in data:
                    SysRoleMenu.objects.create(role_id=role_id, menu_id=menu_id)

            # 返回成功响应
            return JsonResponse({
                'code': '00000',
                'msg': '菜单分配成功',
                'data': {}
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': '10007',
                'msg': '请求体格式错误'
            }, status=400)

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)

class UpdateRoleStatusView(APIView):
    def put(self, request, role_id, *args, **kwargs):
        # 获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 获取 Query 参数中的 status
            status = request.GET.get('status')
            if status is None:
                return JsonResponse({
                    'code': '10006',
                    'msg': '状态参数为必填项'
                }, status=400)

            # 查找角色，如果不存在则返回错误
            role = SysRole.objects.get(id=role_id)

            # 更新角色状态
            role.status = int(status)
            role.save()

            return JsonResponse({
                'code': '00000',
                'msg': '角色状态更新成功',
                'data': {}
            })

        except SysRole.DoesNotExist:
            return JsonResponse({
                'code': '10007',
                'msg': '角色不存在'
            }, status=404)

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)